package api

import (
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/swarm"
	"github.com/docker/docker/client"
	"golang.org/x/crypto/ssh"
)

type NodeInfo struct {
	CPU              int
	RAM              int
	Storage          int
	HasHomePartition bool
}

//// NodeMiddleWare 中间件
//func (handler *Handler) NodeMiddleWare(w http.ResponseWriter, r *http.Request) (cli *client.Client,err error) {
//	endpoint, err := middlewares.FetchEndpoint(r)
//	if err != nil {
//		return  nil, err // Unable to find an environment on request context
//	}
//
//	agentTargetHeader := r.Header.Get(portainer.PortainerAgentTargetHeader)
//
//	cli, err = handler.dockerClientFactory.CreateClient(endpoint, agentTargetHeader, nil)
//	if err != nil {
//		return nil, err // connect to the Docker daemon
//	}
//
//	return cli, nil
//}
//
//// GetNodeList 获取主机列表信息
//func (handler *Handler) GetNodeList(w http.ResponseWriter, r *http.Request) error  {
//	cli, err := handler.NodeMiddleWare(w, r)
//	if err != nil {
//		return errors.New("not in a correct environment")
//	}
//
//	resp := make([]swarm.Node, 0)
//	resp, err = cli.NodeList(context.TODO(), types.NodeListOptions{})
//	fmt.Println(len(resp), "-----------------------")
//	if err != nil {
//		return httperror.NotFound("获取节点信息失败", err)
//	}
//
//	// NodeInspectWithRaw return shorter info about node, but no cpu and mem etc. data
//	// response, sl, err = cli.NodeInspectWithRaw(context.TODO(), resp[0].ID)
//	Info := make([]swarm.Node, 0)
//	for index, _ := range resp {
//		Info = append(Info, resp[index])
//	}
//
//	return nil
//}

func GetNodeList(cli *client.Client) ([]swarm.Node, error) {
	resp := make([]swarm.Node, 0)
	resp, err := cli.NodeList(context.TODO(), types.NodeListOptions{})
	fmt.Println(len(resp), "-----------------------")
	if err != nil {
		return nil, errors.New("获取节点信息失败")
	}

	// NodeInspectWithRaw return shorter info about node, but no cpu and mem etc. data
	// response, sl, err = cli.NodeInspectWithRaw(context.TODO(), resp[0].ID)
	Info := make([]swarm.Node, 0)
	for index, _ := range resp {
		Info = append(Info, resp[index])
	}

	return Info, nil
}

// TestConnection 测试主机连接
func TestConnection(ip, port, password string) bool {
	config := ssh.ClientConfig{
		Timeout:         time.Second * 6,
		User:            "root",
		Auth:            []ssh.AuthMethod{ssh.Password(password)},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(), // 用于简单的认证
	}
	// 与服务器建立连接
	client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", ip, port), &config)
	if err != nil {
		log.Println(err)
	}

	defer func() {
		err := client.Close()
		if err != nil {
			fmt.Println("Close ssh client err: ", err.Error())
		}
	}()

	return true
}
